/*
 *  Copyright 2019-2020 dzygod
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package top.dzygod.modules.oa.rest;

import lombok.RequiredArgsConstructor;
import org.springframework.http.MediaType;
import top.dzygod.annotation.Log;
import top.dzygod.modules.oa.domain.LocalStorage;
import top.dzygod.modules.oa.service.dto.LocalStorageQueryCriteria;
import top.dzygod.modules.system.domain.Dept;
import top.dzygod.modules.system.service.DeptService;
import top.dzygod.modules.system.service.UserService;
import top.dzygod.modules.system.service.dto.DeptDto;
import top.dzygod.modules.system.service.dto.UserDto;
import top.dzygod.modules.oa.service.LocalStorageService;
import top.dzygod.modules.oa.service.MinioService;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.*;
import org.springframework.web.multipart.MultipartFile;
import top.dzygod.modules.system.service.dto.UserQueryCriteria;
import top.dzygod.utils.PageUtil;
import top.dzygod.utils.SecurityUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;

/**
* @author dzyGod
* @date 2019-09-05
*/
@RestController
@RequiredArgsConstructor
@Api(tags = "工具：本地存储管理")
@RequestMapping("/api/localStorage")
public class LocalStorageController {

    private final LocalStorageService localStorageService;

    @Resource
    private MinioService minioService;
    @Resource
    private UserService userservice;
    @Resource
    private DeptService deptService;



    @ApiOperation("查询文件")
    @GetMapping
    @PreAuthorize("@el.check('storage:list')")
    public ResponseEntity<Object> query(LocalStorageQueryCriteria criteria, Pageable pageable){
        Long userId = SecurityUtils.getCurrentUserId();
        UserDto user = userservice.findById(userId);
        // 是否有超管权限,不是超管只能查询当前账号提交的文件
        Boolean hasRole = user.getRoles().stream().map(role -> role.getId() == 1L).findFirst().orElse(false);

        // 超管首页入口处理
        if (hasRole && Objects.nonNull(criteria.getProjectId())) {
            UserQueryCriteria userQueryCriteria = new UserQueryCriteria();
            // 查询系统ids
            Set<Long> systemIds = deptService.findByPid(criteria.getProjectId())
                    .stream().map(Dept::getId).collect(Collectors.toSet());
            if (!systemIds.isEmpty()) { userQueryCriteria.setDeptIds(systemIds); }
            // 根据项目id查询所有系统关联的用户
            final Set<Long> userIds = userservice.queryAll(userQueryCriteria)
                    .stream().map(UserDto::getId).collect(Collectors.toSet());
            // 没有文件，那就返回个空
            if (userIds.isEmpty()) {
                HashMap<String, Object> map = new LinkedHashMap<>(2);
                map.put("content", Collections.emptyList());
                map.put("totalElements", 0);
                return new ResponseEntity<>(map, HttpStatus.OK);
            }
            criteria.setUserIds(userIds);
            return new ResponseEntity<>(localStorageService.queryAll(criteria,pageable),HttpStatus.OK);
        }

        // 超管仅仅查询
        if (hasRole) {
            return new ResponseEntity<>(localStorageService.queryAll(criteria,pageable),HttpStatus.OK);
        }

        criteria.setUserId(userId);
        return new ResponseEntity<>(localStorageService.queryAll(criteria,pageable),HttpStatus.OK);
    }

    @Log("导出数据")
    @ApiOperation("导出数据")
    @GetMapping(value = "/download")
    @PreAuthorize("@el.check('storage:list')")
    public void download(HttpServletResponse response, LocalStorageQueryCriteria criteria) throws IOException {
        localStorageService.download(localStorageService.queryAll(criteria), response);
    }

    @ApiOperation("上传文件")
    @PostMapping
    @PreAuthorize("@el.check('storage:add')")
    public ResponseEntity<Object> create(@RequestParam String category, @RequestParam String name, @RequestParam("file") MultipartFile file){
        // minio实现对象存储
        minioService.storeFile("project", categoryHandler(category), name, file);
        return new ResponseEntity<>(HttpStatus.CREATED);
    }


    @ApiModelProperty("下载文件")
    @PostMapping("/download")
    @PreAuthorize("@el.check('storage:add')")
    public void download(@RequestParam("category") String category,
                         @RequestParam("objectName") String objectName,
                         @RequestParam("fileName") String fileName, HttpServletResponse response) throws Exception {
        byte[] buffer = minioService.getFile("project", category, objectName);
        response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
        response.setHeader("Content-disposition", "attachment; filename=\"" + URLEncoder.encode(fileName, "UTF-8") + "\"");
        response.getOutputStream().write(buffer);
        response.flushBuffer();
        response.getOutputStream().close();
    }

    @ApiOperation("修改文件")
    @PutMapping
    @PreAuthorize("@el.check('storage:edit')")
    public ResponseEntity<Object> update(@Validated @RequestBody LocalStorage resources){
        localStorageService.update(resources);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @Log("多选删除")
    @DeleteMapping
    @ApiOperation("多选删除")
    public ResponseEntity<Object> delete(@RequestBody Long[] ids) {
        localStorageService.deleteAll(ids);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    /**
     * minio上传路径处理
     * @param category 文件夹名
     * @return 处理后的文件夹名
     */
    private String categoryHandler(String category) {

        // 用户id查询部门，将用户关联部门与用户名组成文件夹
        Long id = SecurityUtils.getCurrentUserId();
        UserDto user = userservice.findById(id);
        DeptDto system = deptService.findById(user.getDept().getId());

        // 处理部门,系统为空说明当前用户关联部门非系统
        if (Objects.isNull(system.getSystem())) {
            throw new RuntimeException("不允许未关联系统的用户上传文件");
        }

        DeptDto project = deptService.findById(system.getPid());
        DeptDto group = deptService.findById(project.getPid());

        String systemName = system.getName();
        String projectName = project.getName();
        String groupName = group.getName();

        return groupName + "/" + projectName + "/" + systemName + "/" + category;
    }

}
